package com.haisen.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 *websocket,支持群发，点对点通讯
 *
 */
@Component
@Slf4j
public class WebSocketService  {

    //使用SimpMessagingTemplate 向浏览器发送消息
    @Autowired
    private  SimpMessagingTemplate template;
/*

    //此处是解决无法注入的关键
    private  ApplicationContext applicationContext;
*/

    /**
     * 群发消息
     * @throws Exception
     */
    public  void sendMessage(String message){
        try {
            template.convertAndSend("/topic/getResponse",message);
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 点对点发送短信
     * 定义了2个域，queue点对点，topic群发
     */
    public  void SendMessageToUser(String username,String message) {
        try {
            log.info("消息模板，发送消息：to"+username+",消息="+message);
            template.convertAndSendToUser(username,
                    "/queue/notifications", message);
        } catch (Exception e){
            e.printStackTrace();
        }


    }
}
